#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
import os
from threading import Lock

class Recorder:
    """
    简单的数据记录器，用于记录浏览器操作日志
    """
    
    def __init__(self, log_file="browser_logs.txt"):
        """
        初始化记录器
        
        Args:
            log_file: 日志文件路径
        """
        self.log_file = log_file
        self.lock = Lock()  # 线程锁，确保多线程写入安全
        
        # 确保日志文件所在目录存在
        log_dir = os.path.dirname(log_file)
        if log_dir and not os.path.exists(log_dir):
            os.makedirs(log_dir)
    
    def log(self, message):
        """
        记录日志消息
        
        Args:
            message: 要记录的消息
        """
        timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        log_entry = f"[{timestamp}] {message}"
        
        # 使用线程锁确保写入操作是线程安全的
        with self.lock:
            with open(self.log_file, "a", encoding="utf-8") as f:
                f.write(log_entry + "\n")
                
        print(log_entry)  # 同时在控制台输出
    
    def clear_logs(self):
        """清空日志文件"""
        with self.lock:
            with open(self.log_file, "w", encoding="utf-8") as f:
                f.write("")
                
    def get_logs(self):
        """获取所有日志内容"""
        if not os.path.exists(self.log_file):
            return []
            
        with self.lock:
            with open(self.log_file, "r", encoding="utf-8") as f:
                return f.readlines() 